#!/usr/bin/env python
import click
from flask import request
from flask_migrate import Migrate

from xshare import create_app, db
from common.log import log
from xshare.model.about import About
from xshare.model.xInfo import XInfo
from xshare.model.user import User
from xshare.model.club import Club
from xshare.model.post import Post
from xshare.model.admin import Admin

app = create_app()
migrate = Migrate(app, db)


# Global variables to jiajia2 environment:
app.jinja_env.globals['XInfo'] = XInfo
app.jinja_env.globals['About'] = About
app.jinja_env.globals['Club'] = Club
app.jinja_env.globals['Post'] = Post
app.jinja_env.globals['User'] = User
app.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = False


# 请每一次请求之后都会调用，会接受一个参数，参数是服务器出现的错误信息
@app.before_request
def before_request():
    # ip = request.remote_addr
    # url = request.url
    # print(ip, url)
    log.info(request)


# # 请每一次请求之后都会调用，会接受一个参数，参数是服务器出现的错误信息
# @app.teardown_request
# def teardown_request(response):
#     print(response.text)
#     log.info()


@app.cli.command("deploy")
@click.argument("deploy_type")
def deploy(deploy_type):
    from flask_migrate import upgrade
    # upgrade()

    if deploy_type == 'product':
        XInfo.insert_blog_info()
        User.insert_user(email='nxshare@nxshare.com', username='nxshare',
                         password='Nxshare123')
        Admin.insert_admin(email='admin@nxshare.com', username='admin',
                           password='Nxshare123')
        Club.generate_club()
        Post.insert_post()

    if deploy_type == 'test':
        XInfo.insert_blog_info()
        User.insert_user(email='nxshare@nxshare.com', username='nxshare',
                          password='Nxshare123')
        Admin.insert_admin(email='admin@nxshare.com', username='admin',
                           password='Nxshare123')
        Club.generate_club()
        Post.insert_post()


if __name__ == '__main__':
    app.debug = True
    urls = app.url_map
    print(urls)
    app.run()
    # from gevent.pywsgi import WSGIServer
    #
    # http_server = WSGIServer(('0.0.0.0', 5000), app)
    # http_server.serve_forever()